import socket
import sys,os
# BASE_DOR = os.path.dirname(os.path.abspath(__file__))
# sys.path.append(BASE_DOR)
from application import app1


class WebServer(object):

    def __init__(self, port):
        tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)        
        tcp_socket.bind(('', port))
        tcp_socket.listen(128)
        self.tcp_socket = tcp_socket

    def start(self):
        print('启动成功')
        while True:
            new_socket, ip_port = self.tcp_socket.accept()
            print('%s上线啦' %str(ip_port))
            self.request_heandler(new_socket, ip_port)

    def request_heandler(self, new_socket, ip_port):
        app1.application(new_socket, ip_port)
        new_socket.close()


def main():
    argv_list = sys.argv
    print(argv_list)
    if len(argv_list) != 2:
        print('参数有误正确的格式是：python3 xxx.py 端口号')
        return
    if not argv_list[1].isdigit():
        print('端口号必须是数字')
        return
    port = int(argv_list[1])
    ws = WebServer(port)
    ws.start()


if __name__ == '__main__':
    main()
